package com.zhouqinuan.spring.cloud.develop.framework.web.config;

import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.zhouqinuan.spring.cloud.develop.framework.web.ControllerResponseBodyAdvice;

import feign.RequestInterceptor;
import feign.RequestTemplate;

@Configuration
public class WebConfiguration {

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory();
        factory.setReadTimeout(5000); // ms
        factory.setConnectTimeout(2000); // ms
        factory.setWriteTimeout(10000);

        return factory;
    }

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        return restTemplate;
    }

    /**
     * feign调用传递header
     * 
     */
    @Bean
    public RequestInterceptor headerInterceptor() {
        
        return new RequestInterceptor() {

            @Override
            public void apply(RequestTemplate requestTemplate) {
                
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes == null) {
                    return;
                }

                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                
                if (headerNames != null) {
                    
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        requestTemplate.header(name, values);
                    }
                }

            }
        };
    }

    @Bean
    public ControllerResponseBodyAdvice controllerResponseBodyAdvice() {
        return new ControllerResponseBodyAdvice();
    }
}
